<?php
/**
 * Created by PhpStorm.
 * User: Dave
 * Date: 2018/4/8
 * Time: 14:40
 */

namespace Biz\service;

use Biz\model\PhotoRelaGoods as BizMPhotoRelaGoods;
use Doraemon\model\PhotoRelaGoods as mPhotoRelaGoods;
use Doraemon\service\Photos as sPhotos;
use Doraemon\tools\IdParse;
use Doraemon\cache\BlackList;
use Doraemon\service\Like as sLike;
use Doraemon\model\Like as mLike;
use Doraemon\service\Favorite as sFavorite;
use Doraemon\service\User as sUser;
use Doraemon\service\Follow as sFollow;
use Doraemon\service\CommonEmblem as sCommonEmblem;
use Doraemon\service\Activity as sActivity;
use Doraemon\cache\PhotoCounter as cPhotoCounter;
use Doraemon\cache\PhotoJoinActivity as cPhotoJoinActivity;
use Doraemon\model\PhotoJoinGuide as mPhotoJoinGuide;
use Doraemon\model\Article as mArticle;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Filter;
use Doraemon\tools\Checker;
use Doraemon\tools\Hhzurl;
use Biz\model\GoodsBasicInfo as mGoodsBasicInfo;
use Doraemon\tools\MentionTools;

/**
 * @deprecated
 */
class RelatePhotos
{
    const DEFAULT_PAGE = 19;
    const STATUS_PRIVATE = 11;
    public static function getPhotos($wikiId, $searchType, $page, $uid = 0){

        $photoIdData = mPhotoRelaGoods::getPhotoListByGoodsId($wikiId, [], $page, self::DEFAULT_PAGE);
        $sortphotos  = [];
        $is_over = 1;
        if (!empty($photoIdData)){

        	$sortphotos = self::getSortPhotos($searchType, $photoIdData, $uid);
        	count($photoIdData) == self::DEFAULT_PAGE && $is_over = 0;
        }

        $data = array(
            'rows' => ($sortphotos && is_array($sortphotos)) ? array_values($sortphotos) : array(),
            'is_over' => $is_over,
        );

        return $data;
    }

    private static function getSortPhotos($searchType, $photosids, $uid)
	{
		$sortphotos = [];
		if ($photosids) {
//			$data = self::getPhotoInfos($photosids, $uid);
			$data = sPhotos::getPhotoInfos($photosids, $uid);
			if (!empty($data)){
				// 过滤B级用户
				$uids = array_map([new IdParse(), 'getUid'], $photosids);
				$filter_B_level_photos = self::filterBLevelUser($uids, $data);

				// 过滤仅自己可见图片
				$filter_photos = self::photosOnService($filter_B_level_photos);

				if ($searchType == 1){

					$sortphotos = self::arrayHotSort(array_values($filter_photos), 'desc');
				} else {

					$sortphotos = self::arrayTimeSort(array_values($filter_photos), 'desc');
				}
			}

//			count($sortphotos) == self::DEFAULT_PAGE && $is_over = 0;
		}

		return $sortphotos;

	}

	public static function getPhotosByGid($goodsId, $searchType, $page, $uid = 0)
	{
		$photos_ids = BizMPhotoRelaGoods::getPhotosListByGoodsId($goodsId, $page, self::DEFAULT_PAGE);
		$data = [
			'rows' => [],
			'is_over' => 1
		];
		if ($photos_ids) {
			$sortPhotos = self::getSortPhotos($searchType, $photos_ids, $uid);
			$data['rows'] = $sortPhotos && is_array($sortPhotos) ? array_values($sortPhotos) : [] ;
			$data['is_over'] = count($photos_ids) == self::DEFAULT_PAGE  ?  0 : 1;
		}

		return $data;

	}


	public static function arrayHotSort($array, $sort='asc') {

		$newArr = $valArr = array();
		foreach ($array as $key=>$value) {
			$sum['comment'] = $value['counter']['comment'];
			$sum['like'] = $value['counter']['like'];
			$sum['favorite'] = $value['counter']['favorite'];
			$valArr[$key] = array_sum($sum);
		}

		($sort == 'asc') ?  asort($valArr) : arsort($valArr);
		reset($valArr);
		foreach($valArr as $key=>$value) {
			$newArr[$key] = $array[$key];
		}
		return $newArr;
	}

	public static function arrayTimeSort($array, $sort='asc') {

		$newArr = $valArr = array();
		foreach ($array as $key=>$value) {

			$valArr[$key] = $value['photo_info']['addtime'];
		}
		($sort == 'asc') ?  asort($valArr) : arsort($valArr);
		reset($valArr);
		foreach($valArr as $key=>$value) {

			$newArr[$key] = $array[$key];
		}
		return $newArr;
	}

	private static function filterBLevelUser($uids, $infos)
	{
		$black_uids = BlackList::getBlackUser($uids);
		$filter_B_level_photos = $infos;
		if (!empty($black_uids)) {
			$filter_B_level_photos = array_filter($infos, function ($info) use ($black_uids){
				return !in_array($info['user_info']['uid'], $black_uids);
			});
		}
		return $filter_B_level_photos;
	}

	public static function photosOnService($photo_list, $active_uid = 0)
	{
		$data = array();
		if ($photo_list && is_array($photo_list)){
			$data = array_filter($photo_list, function ($photo) use ($active_uid){
				if ($active_uid == $photo['user_info']['uid']) {
					return true;
				}
				return  $photo['photo_info']['status'] != self::STATUS_PRIVATE;
			});
		}
		return $data;
	}

	/**
	 * 获取图片信息
	 * @param $photoIds array
	 * @param int $uid
	 * @param bool $hignQuality
	 * @param string $tag
	 * @return array
	 */
	public static function getPhotoInfos($photoIds, $uid, $hignQuality = false, $tag = '')
	{
		$result = array();
		if (!empty($photoIds) && is_array($photoIds)) {
			$photos = sPhotos::getPhotos($photoIds);
            foreach($photos as $value) {
                if($value['admin_score'] > 10 || $value['admin_score'] < 1) {
                    $aPhotoRows[] = $value;
                }
            }
			if ($aPhotoRows && is_array($aPhotoRows)) {
				// 存储uid集，后续获取用户信息
				$aUids = array();
				foreach ($aPhotoRows as $k => $row) {
					if (!$row) {
						unset($aPhotoRows [$k]);
						continue;
					}
					$aUids [] = $row ['uid'];
				}
				$aUids = array_unique($aUids);
				$aUids = array_filter($aUids);
				$aIsLiked = $aIsFavorited = array();
				if ($uid) {
					$aIsLiked = sLike::isLikedMulti($uid, $photoIds, mLike::LIKE_TYPE_PHOTO);
					$aIsFavorited = sFavorite::isFavoritedMulti($uid, $photoIds, mLike::LIKE_TYPE_PHOTO);
					$is_follows = sFollow::isFollowedMulti($uid, $aUids);
				}
				$aUserList = sUser::getUsers($aUids);

				$AdornEmblems = sCommonEmblem::showEmblemByUids($aUids);

				$aPhotoid2Counter = cPhotoCounter::getMulti($photoIds);
				$activity_list = cPhotoJoinActivity::getMulti($photoIds);
				//判断活动是否是有奖征集
				$activity_list = sActivity::getMultiActivityRewardInfos($activity_list);
				$mention_user_list = self::getMentionUserList($aPhotoRows);

				foreach ($aPhotoRows as $row) {
					$is_liked = (isset($aIsLiked [$row ['id']]) && $aIsLiked [$row ['id']] == 1) ? 1 : 0;
					if (!isset($aUserList [$row ['uid']])) {
						continue;
					}
					//获取图片是否关联文章,如果图片没有关联文章则查询是否有关联指南，如果都没有那么说明图片没有关联任何东西
					$is_guide_relevance = 0;
					$relevance_data = mPhotoJoinGuide::getJoinGuideByPhotoId($row ['id']);
					if ($relevance_data) {
						$is_guide_relevance = 1;
					}
					$is_article_relevance = 0;
					if ((int)$row['type'] == 1) {
						$article_data = mArticle::getArticle($row['article_id']);
						if (isset($article_data['status']) && ($article_data['status'] !== '0')) {
							$is_article_relevance = 1;
						}
					}
					$row['is_relevance'] = (int)($is_article_relevance || $is_guide_relevance);
					$tags = json_decode($row ['img_tags'], true);
					$tags = (is_array($tags)) ? $tags : array();
					$tags = array_filter($tags);
					$tags = array_values($tags);

					$img_mode = ($hignQuality) ? ImgUrl::IMAGE_SIZE_SQ_BEST_PHONE : ImgUrl::IMAGE_SIZE_SQ_PHONE;
					$result [$row ['id']] = array(
						'id' => $row ['id'],
						'user_info' => array_merge($aUserList[$row ['uid']], ['is_follow' => isset($is_follows[$row['uid']]) && $is_follows[$row['uid']] ? 1 : 0, 'emblem_adorn' => $AdornEmblems[$row['uid']]]),
						'photo_info' => array(
							'pic_url' => ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $row ['pic_id'], $img_mode),
							'new_pic_url' => ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $row ['pic_id'], ImgUrl::IMAGE_SIZE_ORI_NPHONE),
							'thumb_pic_url' => ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $row ['pic_id'], ImgUrl::IMAGE_SIZE_SQ_THUMB),
							'ori_pic_url' => ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $row ['pic_org_id'], ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG),
							'o_500_url' => ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $row ['pic_id'], ImgUrl::IMAGE_SIZE_O_500),
							'remark' => MentionTools::getMentionContent($row['remark'], self::getMentionUids($row), $mention_user_list),
							'mention_list' => MentionTools::getShowMentionUsers($row['remark'], self::getMentionUids($row), $mention_user_list),
							'house_type' => $row ['house_type'],
							'is_liked' => $is_liked,
							'status' => $row ['status'],
							'is_relevance' => ( int )$row ['is_relevance'],
							'has_goods' => ( int )$row ['has_goods'],
							'is_favorited' => isset($aIsFavorited [$row ['id']]) && $aIsFavorited [$row ['id']] ? 1 : 0,
							'is_join_article' => ( int )Checker::isActivityid($row ['article_id']),
							'share_url' => Hhzurl::h5PhotoShow($row ['id']),
							'addtime' => $row ['addtime'],
							'tags' => $tags,
							'id' => $row ['id'],
							'remark_tags' => sPhotos::showTag($row['remark'],$tags)
						),
						'counter' => $aPhotoid2Counter [$row ['id']],
						'activity' => ( object )$activity_list [$row ['id']],
						'share_info' => (object)sPhotos::get_share($aUserList[$row ['uid']]['nick'], $row),
					);
					//是否包含admin_tag
					if ($tag) {
						$photo_tags = array_map('trim', explode(',', $row['admin_tag']));
						$result [$row ['id']]['photo_info']['is_contain_tag'] = (in_array($tag, $photo_tags)) ? 1 : 0;
					}
				}
			}
		}
		return $result;
	}

	public static function RelaGoodsCounter($photoId)
	{
		return (int) BizMPhotoRelaGoods::relaCounter($photoId);
	}

	public static function RelaPhotoType($photoId)
	{
		$relaInfos = BizMPhotoRelaGoods::getGoodsInfoByPhotoId($photoId);

		return array_combine(
			array_column($relaInfos, 'goods_id'),
			array_column($relaInfos, 'type')
		);

	}

	private static function getMentionUserList($photo_list)
	{
		$mention_user_list = [];
		$all_mention_uids = self::getMentionUidsOfList($photo_list);
		if ($all_mention_uids){
			$mention_user_list = sUser::getUsers($all_mention_uids);
		}
		return $mention_user_list;
	}

	private static function getMentionUidsOfList($photo_list)
	{
		$all_mention_uids = [];
		foreach ($photo_list as $photo){
			$mention_uids = MentionTools::getDbMentionUids($photo['remark']);
			if ($mention_uids){
				$all_mention_uids = array_merge($all_mention_uids, $mention_uids);
			}
		}
		$all_mention_uids = array_unique($all_mention_uids);
		return $all_mention_uids;
	}
	private static function getMentionUids($photo)
	{
		$mention_uids = json_decode($photo['mention_uids'], true);
		return ($mention_uids && is_array($mention_uids)) ? $mention_uids : [];
	}

}